package com.nebula.controller.user;

import com.nebula.result.Result;
import com.nebula.service.DishService;
import com.nebula.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品浏览接口")
public class DishController {
    @Autowired
    private DishService dishService;
    private static final String BLOOM_FILTER_NAME = "categoryIdsBloomFilter";
    private static final double FALSE_PROBABILITY = 0.01; // 误判率
    private static final int EXPECTED_INSERTIONS = 1000; // 预计插入的元素数量
    @Autowired
    private RedissonClient redissonClient;

    public void initBloomFilter(List<Long> categoryIds) {
        RBloomFilter<Long> bloomFilter = redissonClient.getBloomFilter(BLOOM_FILTER_NAME);
        // 初始化布隆过滤器
        bloomFilter.tryInit(EXPECTED_INSERTIONS, FALSE_PROBABILITY);
        // 将所有商品ID插入布隆过滤器
        for (Long categoryId : categoryIds) {
            bloomFilter.add(categoryId);
        }
    }


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(Long categoryId) {

        RBloomFilter<Long> bloomFilter = redissonClient.getBloomFilter(BLOOM_FILTER_NAME);
        if (!bloomFilter.contains(categoryId)) {
            return Result.success(null); // 布隆过滤器判断不存在，直接返回null
        }

//        String key = "dish_" + categoryId;
//        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);
//        if (list != null && list.size() > 0){
//            return Result.success(list);
//        }

        List<DishVO> list = dishService.listWithFlavor(categoryId);

//        redisTemplate.opsForValue().set(key,list);

        return Result.success(list);
    }
}
